package com.xbongbong.saas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.FormDataValidateDataHelp;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.pro.enums.errorcodes.UserTeamErrorCodeEnum;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.paas.business.rule.RuleBusinessLogger;
import com.xbongbong.paas.help.ProSaveHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.pojo.AttrValuePojo;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForImport;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.ImportFormDataDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.imports.CellTitlePojo;
import com.xbongbong.paas.pojo.imports.CellValuePojo;
import com.xbongbong.paas.pojo.imports.RowGroupPojo;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.team.TeamDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.LevelUtil;
import com.xbongbong.pro.businessproduct.pojo.dto.BusinessProductListDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.detailtab.dto.DetailTabDataGetDTO;
import com.xbongbong.pro.detailtab.dto.SupplierProductAddDTO;
import com.xbongbong.pro.detailtab.vo.ProductSummaryVO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.InstockErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.permission.enums.UpdateProPermissionAliasEnum;
import com.xbongbong.pro.form.pojo.dto.ChildProductDTO;
import com.xbongbong.pro.form.pojo.dto.EsDataDTO;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.listbatch.pojo.dto.AddLabelDTO;
import com.xbongbong.pro.log.pojo.dto.RuleBusinessLogDTO;
import com.xbongbong.pro.product.pojo.dto.PagingProductDTO;
import com.xbongbong.pro.product.pojo.dto.ProductUpdateDTO;
import com.xbongbong.pro.product.pojo.vo.DetailProductVO;
import com.xbongbong.pro.product.pojo.vo.PagingProductVO;
import com.xbongbong.pro.pushnotify.dto.PushNotifyDeleteDTO;
import com.xbongbong.pro.supplier.pojo.dto.SupplierDeleteBatchDTO;
import com.xbongbong.pro.supplier.pojo.dto.SupplierEditAttrUpdateDTO;
import com.xbongbong.pro.supplier.pojo.dto.SupplierUpdateBatchDTO;
import com.xbongbong.pro.supplier.pojo.dto.SupplierUpdateByBusinessRuleDTO;
import com.xbongbong.pro.supplier.pojo.dto.SupplierUpdateDTO;
import com.xbongbong.pro.supplier.pojo.vo.SupplierDeleteBatchVO;
import com.xbongbong.pro.supplier.pojo.vo.SupplierUpdateBatchVO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierCommunicateDeleteBatchDTO;
import com.xbongbong.pro.suppliercommunicate.pojo.dto.SupplierDynamicAddDTO;
import com.xbongbong.pro.suppliercontact.pojo.dto.SupplierContactDeleteBatchDTO;
import com.xbongbong.pro.supplierproduct.pojo.SupplierProductDeleteBatchDTO;
import com.xbongbong.pro.supplieruser.pojo.dto.SupplierUserDeleteBatchDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.saas.analytical.impl.SupplierValidateAnalyticalServiceImpl;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.PayBalanceEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.SupplierUserEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.PayBalanceEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.product.SupplierProductEnum;
import com.xbongbong.saas.help.ImportHelper;
import com.xbongbong.saas.help.LogHandleHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasDeleteHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.workflow.SupplierHelp;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.SupplierUserModel;
import com.xbongbong.saas.service.PayBalanceService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.PushNotifyService;
import com.xbongbong.saas.service.SupplierCommunicateService;
import com.xbongbong.saas.service.SupplierContactService;
import com.xbongbong.saas.service.SupplierProductService;
import com.xbongbong.saas.service.SupplierService;
import com.xbongbong.saas.service.SupplierUserService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.toolbox.help.LogHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.UserModel;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;


/**
 * 供应商service实现层
 * @author WangJian
 * @date  2019-01-23 20:02
 * @since v1.0
 * @version v1.0
 **/
@Service("SupplierService")
public class SupplierServiceImpl implements SupplierService{

    private static final Logger LOG = LoggerFactory.getLogger(SupplierServiceImpl.class);

    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private SupplierUserService supplierUserService;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private SupplierContactService supplierContactService;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private ProductService productService;
    @Resource
    private ImportHelper importHelper;
    @Resource
    private SupplierProductService supplierProductService;
    @Resource
    private PushNotifyService pushNotifyService;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private SupplierCommunicateService supplierCommunicateService;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    @Lazy
    private RuleBusinessLogger ruleBusinessLogger;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private FormDataValidateDataHelp formDataValidateDataHelp;
    @Resource
    private SupplierUserModel supplierUserModel;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private PaasEsModel paasEsModel;

    @Resource
    private PaasProcessDataModel paasProcessDataModel;
    @Resource
    private PayPlanSheetService payPlanSheetService;
    @Resource
    private PayBalanceService payBalanceService;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private LogHelp logHelp;
    @Resource
    private LogHandleHelp logHandleHelp;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private SupplierValidateAnalyticalServiceImpl supplierAnalyticalService;
    @Resource
    private SupplierHelp supplierHelp;
    @Resource
    private TeamDataHelp teamDataHelp;
    @Resource
    private UserTeamHelp userTeamHelp;

    /**
     * 供应商保存前saas特殊校验
     *
     * @param validateDataDTO saas特殊校验数据入参
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        supplierAnalyticalService.beforeSave(validateDataDTO);
    }





    /**
     * 供应商保存后逻辑
     *
     * @param saasFormSaveDTO saas保存数据
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public AfterSavePojo afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        AfterSavePojo afterSavePojo = new AfterSavePojo();
        String corpid = saasFormSaveDTO.getCorpid();
        // 保存供应商负责人
        // 团队保存
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), false);
//        userTeamService.saveUserTeam(saasFormSaveDTO);

        PaasFormDataEntity paasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        Long supplierId = paasFormDataEntity.getId();
        JSONObject dataList = paasFormDataEntity.getData();
        String supplierName = dataList.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
        JSONArray productIdArray = dataList.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        // 保存供应商关联产品
//        if (saasFormSaveDTO.getIsNew() || saasFormSaveDTO.getSaasNeedRedundantAttrPoJo().getAttrCanSee(SupplierEnum.PRODUCT_LIST.getAttr())) {
        if (BasicConstant.ONE.equals(saasFormSaveDTO.getIsImport()) || (Objects.nonNull(productIdArray) && !productIdArray.isEmpty())) {
            //新建或编辑可见产品字段
            Runnable runnable = () -> {
                try {
                    saveSupplierProduct(saasFormSaveDTO.getIsNew(), corpid, supplierId, supplierName, productIdArray);
                } catch (Exception e) {
                    LOG.error("保存供应商关联产品", e);
                }
            };
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
        }
        //项目日志记录(供应商新建的动态数据从这里拿的)
        if(saasFormSaveDTO.getIsNew()){
            try {
                String supplieName = "";
                Map<String, String> userNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                String communicateMemo = "";
                if(Objects.nonNull(paasFormDataEntity.getData())){
                    supplieName = paasFormDataEntity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                }
                String operate = Objects.equals(saasFormSaveDTO.getIsImport(), 1) ? I18nMessageUtil.getMessage(I18nStringConstant.IMPORTED) : I18nMessageUtil.getMessage(I18nStringConstant.ADD);
                if (Objects.nonNull(saasFormSaveDTO.getOldPaasFormDataEntity())){
                    String creatorId = saasFormSaveDTO.getOldPaasFormDataEntity().getCreatorId();
                    userNameMap = userModel.getUserNameMap(corpid, Collections.singletonList(creatorId));
                    communicateMemo = userNameMap.get(creatorId) + operate + I18nMessageUtil.getMessage(CommonConstant.SUPPLIER) + " :" + supplieName;
                }
                SupplierDynamicAddDTO supplierDynamicAddDTO = new SupplierDynamicAddDTO();
                supplierDynamicAddDTO.setCorpid(saasFormSaveDTO.getCorpid());
                supplierDynamicAddDTO.setUserId(paasFormDataEntity.getCreatorId());
                supplierDynamicAddDTO.setSupplierId(supplierId);
                supplierDynamicAddDTO.setSupplierName(supplierName);
                supplierDynamicAddDTO.setMemo(communicateMemo);
                supplierDynamicAddDTO.setCommunicateBusinessText(supplieName);//CommunicateBusinessText 是在动态展示时用的，合同是流水号，人一般是名称，eg：供应商：周杰伦
                supplierDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
                supplierDynamicAddDTO.setDataId(supplierId);//动态数据获取就是 依赖 dataId 和 businessType
                supplierCommunicateService.addSupplierDynamic(supplierDynamicAddDTO);
            }catch (XbbException e){
                LOG.error("供应商新增项目日志记录失败",e);
            }
        }
        return afterSavePojo;
    }

    /**
     * 更新产品
     * @param supplierId
     * @param supplierName
     * @param corpid
     * @param influenceProductIdList
     * @param productSavePojoList
     * @throws XbbException
     */
    private void updateProductLinkSupplier(Long supplierId, String supplierName, String corpid, Set<Long> influenceProductIdList, List<Long> productSavePojoList) throws XbbException {
        HashMap<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("productIdIn", influenceProductIdList);
        param.put("negSupplierId",supplierId);
        List<SupplierProductEntity> supplierProducts = supplierProductModel.findEntitys(param);
        Set<Long> supplierIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long,List<Long>> supplierProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (SupplierProductEntity entity : supplierProducts) {
            supplierIdSet.add(entity.getSupplierId());
            List<Long> list = supplierProductMap.getOrDefault(entity.getProductId(),new ArrayList<>());
            list.add(entity.getSupplierId());
            supplierProductMap.put(entity.getProductId(),list);
        }
        for (Long productId : productSavePojoList){
            List<Long> list = supplierProductMap.getOrDefault(productId,new ArrayList<>());
            list.add(supplierId);
            supplierProductMap.put(productId,list);
        }
        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        supplierNameMap.put(supplierId,supplierName);
        if (!supplierIdSet.isEmpty()){
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),supplierIdSet));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            fieldList.add(StringConstant.JSON_DATA);
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER,boolQueryBuilder,PaasFormDataEntityExt.class,fieldList);
            for (PaasFormDataEntityExt entityExt : paasFormDataEntityExtList){
                JSONObject data = entityExt.getData();
                String name = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                supplierNameMap.put(entityExt.getDataId(),name);
            }
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        BoolQueryBuilder innerBoolQueryBuilder = boolQuery();
        innerBoolQueryBuilder.should(termsQuery(FieldTypeEnum.DATAID.getAlias(),influenceProductIdList));
        innerBoolQueryBuilder.should(termsQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID),influenceProductIdList));
        innerBoolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
        boolQueryBuilder.filter(innerBoolQueryBuilder);
        List<String> productFieldList = new ArrayList<>();
        productFieldList.add(StringConstant.DATA_ID);
        productFieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
        List<PaasFormDataEntityExt> productList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT,boolQueryBuilder,PaasFormDataEntityExt.class,productFieldList);
        List<UpdateDataEntity>  updateDataEntityList = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : productList){
            JSONObject data = entityExt.getData();
            Long parentId = data.getLong(ProductEnum.PARENT_ID.getAttr());
            Long productId;
            if (Objects.equals(parentId,0L)){
                productId = entityExt.getDataId();
            }else {
                productId = parentId;
            }
            List<String> supplierIdArray = new ArrayList<>();
            List<String> supplierNameArray = new ArrayList<>();
            List<Long> supplierIdList = supplierProductMap.getOrDefault(productId,new ArrayList<>());
            for (Long supplier : supplierIdList){
                supplierIdArray.add(supplier.toString());
                supplierNameArray.add(supplierNameMap.getOrDefault(supplier,""));
            }
            data.put(ProductEnum.SUPPLIER.getAttr(),supplierIdArray);
            data.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), supplierNameArray);
            updateDataEntityList.add(ExplainUtil.getUpdateData(entityExt.getDataId(),data,corpid));
        }
        if (!updateDataEntityList.isEmpty()){
            productModel.updateBatch(updateDataEntityList,corpid);
        }
    }

    /**
     * 保存供应商产品
     * @param corpid 公司Id
     * @param supplierId 供应商ID
     * @param supplierName
     * @param productArray 产品Id
     * @throws XbbException 异常
     */
    private void saveSupplierProduct(boolean isNew, String corpid, Long supplierId, String supplierName, JSONArray productArray) throws XbbException {
        supplierHelp.saveSupplierProduct(isNew, corpid, supplierId, supplierName, productArray);
    }


    private void setProductSupplier(String corpid, Long supplierId, String supplierName, List<UpdateDataEntity> updateDataEntityList, PaasFormDataEntity paasFormDataEntity, List<String> supplierIdArr, List<String> supplierNameArr) {
        if (Objects.nonNull(supplierIdArr) && !supplierIdArr.contains(supplierId.toString())) {
            supplierIdArr.add(supplierId.toString());
            supplierNameArr.add(supplierName);
            JSONObject data = new JSONObject();
            data.put(ProductEnum.SUPPLIER.getAttr(), supplierIdArr);
            data.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), supplierNameArr);
            updateDataEntityList.add(ExplainUtil.getUpdateData(paasFormDataEntity.getId(), data, corpid));
        }
    }

    /**
     * 更新产品表单数据的Supplier字段
     *
     * @param corpid                    公司id
     * @param influenceProductIdList    受影响的产品
     * @author GuoJun.HU
     * @since V1.0
     * @date 2019/7/3 10:53
     */
    @Override
    public void updateProductLinkSupplier(String corpid, Set<Long> influenceProductIdList) throws XbbException {
        HashMap<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("del", 0);
        param.put("productIdIn", influenceProductIdList);
        List<SupplierProductEntity> supplierProducts = supplierProductModel.findEntitys(param);

        List<Long> supplierIdList = new ArrayList<>();
        supplierIdList.add(-1L);
        Map<Long, List<SupplierProductEntity>> supplierProductRelativeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (SupplierProductEntity supplierProduct : supplierProducts) {
            supplierIdList.add(supplierProduct.getSupplierId());
            List<SupplierProductEntity> supplierProductList = supplierProductRelativeMap.get(supplierProduct.getProductId());
            if (Objects.isNull(supplierProductList)) {
                supplierProductList = new ArrayList<>();
            }
            supplierProductList.add(supplierProduct);
            supplierProductRelativeMap.put(supplierProduct.getProductId(), supplierProductList);
        }

        EsDataDTO esDataDTO = new EsDataDTO();
        esDataDTO.setCorpid(corpid);
        esDataDTO.setDel(0);
        esDataDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
        esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        esDataDTO.setFieldList(null);
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        conditionsEntityExtList.add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(supplierIdList), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
        esDataDTO.setConditionsEntityExtList(conditionsEntityExtList);
        PaasFormDataEsListVO supplierEsDataList = paasFormDataService.getEsDataList(esDataDTO);
        List<PaasFormDataEntityExt> supplierEsList = supplierEsDataList.getPaasFormDataESList();
        // 构建供应商id和供应商名称的关联关系
        Map<Long, String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (PaasFormDataEntityExt supplierEsData : supplierEsList) {
            String supplierName = supplierEsData.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());
            supplierNameMap.put(supplierEsData.getDataId(), supplierName);
        }

        // 获取父产品
        esDataDTO = new EsDataDTO();
        esDataDTO.setCorpid(corpid);
        esDataDTO.setDel(0);
        esDataDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        esDataDTO.setFieldList(null);
        conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        conditionsEntityExtList.add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(influenceProductIdList), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
        esDataDTO.setConditionsEntityExtList(conditionsEntityExtList);
        PaasFormDataEsListVO esDataList = paasFormDataService.getEsDataList(esDataDTO);
        List<PaasFormDataEntityExt> productFormDataList = esDataList.getPaasFormDataESList();
        // 获取子产品
        ChildProductDTO childProductDTO = new ChildProductDTO();
        childProductDTO.setCorpid(corpid);
        childProductDTO.setParentProductId(new ArrayList<>(influenceProductIdList));
        PaasFormDataEsListVO childEsDataList = productService.getChildProductList(childProductDTO);
        List<PaasFormDataEntityExt> childProductFormDataList = childEsDataList.getPaasFormDataESList();
        // 所有需要更新supplier字段的产品数据
        productFormDataList.addAll(childProductFormDataList);

        List<ProductUpdateDTO> productUpdateList = new ArrayList<>();
        for (PaasFormDataEntityExt productFormData : productFormDataList) {
            JSONObject dataObj = productFormData.getData();
            Long dataId = productFormData.getDataId();
            Long parentId = dataObj.getLong(ProductEnum.PARENT_ID.getAttr());
            if (Objects.equals(parentId, 0L)) {
                parentId = dataId;
            }
            List<SupplierProductEntity> supplierProductList = supplierProductRelativeMap.get(parentId);
            if (Objects.isNull(supplierProductList)) {
                supplierProductList = new ArrayList<>();
            }
            List<String> supplierIdArray = new ArrayList<>();
            List<String> supplierNameArray = new ArrayList<>();
            for (SupplierProductEntity supplierProduct : supplierProductList) {
                Long supplierId = supplierProduct.getSupplierId();
                if (supplierNameMap.containsKey(supplierId) && StringUtil.isNotEmpty(supplierNameMap.get(supplierId))) {
                    supplierIdArray.add(Objects.toString(supplierId, ""));
                    supplierNameArray.add(Objects.toString(supplierNameMap.get(supplierId), ""));
                }
            }
            dataObj.put(ProductEnum.SUPPLIER.getAttr(), supplierIdArray);
            dataObj.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), supplierNameArray);

            JSONObject updateObj = new JSONObject();
            updateObj.put(ProductEnum.SUPPLIER.getAttr(), supplierIdArray);
            updateObj.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), supplierNameArray);
            ProductUpdateDTO productUpdateDTO = new ProductUpdateDTO();
            productUpdateDTO.setId(dataId);
            productUpdateDTO.setData(updateObj);
            productUpdateList.add(productUpdateDTO);
        }
        if (!productUpdateList.isEmpty()) {
            List<UpdateDataEntity> updateDataList = new ArrayList<>();
            productUpdateList.forEach(item -> updateDataList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid)));
            if (!updateDataList.isEmpty()) {
                productModel.updateBatch(updateDataList, corpid, WriteRequest.RefreshPolicy.NONE);
            }
        }
    }

    @Override
    public void updateProductLinkSupplier(String corpid, SupplierProductEntity supplierProductEntity) throws XbbException {
        SupplierEntityExt supplierEntity = supplierModel.getByKey(supplierProductEntity.getSupplierId(), corpid);

        // 获取父产品
        EsDataDTO esDataDTO = new EsDataDTO();
        esDataDTO.setCorpid(corpid);
        esDataDTO.setDel(0);
        esDataDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        esDataDTO.setFieldList(null);
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        conditionsEntityExtList.add(EsUtil.packageContions(StringConstant.DATA_ID, Collections.singletonList(supplierProductEntity.getParentId()), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
        esDataDTO.setConditionsEntityExtList(conditionsEntityExtList);
        PaasFormDataEsListVO esDataList = paasFormDataService.getEsDataList(esDataDTO);
        List<PaasFormDataEntityExt> productFormDataList = esDataList.getPaasFormDataESList();
        // 获取子产品
        ChildProductDTO childProductDTO = new ChildProductDTO();
        childProductDTO.setCorpid(corpid);
        childProductDTO.setParentProductId(Collections.singletonList(supplierProductEntity.getParentId()));
        PaasFormDataEsListVO childEsDataList = productService.getChildProductList(childProductDTO);
        List<PaasFormDataEntityExt> childProductFormDataList = childEsDataList.getPaasFormDataESList();
        // 所有需要更新supplier字段的产品数据
        productFormDataList.addAll(childProductFormDataList);
        List<ProductUpdateDTO> productUpdateList = new ArrayList<>();
        for (PaasFormDataEntityExt productFormData : productFormDataList) {
            JSONObject dataObj = productFormData.getData();
            Long dataId = productFormData.getDataId();
            List<String> supplierIdArray = new ArrayList<>();
            List<String> supplierNameArray = new ArrayList<>();
            if (Objects.nonNull(dataObj)) {
                supplierIdArray = dataObj.getJSONArray(ProductEnum.SUPPLIER.getAttr()).toJavaList(String.class);
                supplierNameArray = dataObj.getJSONArray(ProductEnum.SUPPLIER_LINK_TEXT.getAttr()).toJavaList(String.class);
                supplierIdArray.remove(supplierEntity.getId().toString());
                supplierNameArray.remove(supplierEntity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
            }

            JSONObject updateObj = new JSONObject();
            updateObj.put(ProductEnum.SUPPLIER.getAttr(), supplierIdArray);
            updateObj.put(ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), supplierNameArray);
            ProductUpdateDTO productUpdateDTO = new ProductUpdateDTO();
            productUpdateDTO.setId(dataId);
            productUpdateDTO.setData(updateObj);
            productUpdateList.add(productUpdateDTO);
        }
        if (!productUpdateList.isEmpty()) {
            List<UpdateDataEntity> updateDataList = new ArrayList<>();
            productUpdateList.forEach(item -> updateDataList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid)));
            if (!updateDataList.isEmpty()) {
                productModel.updateBatch(updateDataList, corpid, WriteRequest.RefreshPolicy.NONE);
            }
        }
    }

    private void getProductList(List<SupplierProductEntity> supplierProductList,JSONArray productArray,Map<Long, ProductEntityExt> productMap) throws XbbException{
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            if (productMap.containsKey(pageProductId)) {
                SupplierProductEntity productEntity = new SupplierProductEntity();
                productEntity.setProductId(pageProductId);
                productEntity.setUnit(productMap.get(pageProductId).getData().getString(ProductEnum.UNIT.getAttr()));
                supplierProductList.add(productEntity);
            }
        }
    }
    private Map<Long,ProductEntityExt> getProductMap(String corpid,JSONArray productArray){
        List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject object = productArray.getJSONObject(i);
            // 页面传入的产品的id
            Long productId = object.getLong(StringConstant.SAAS_LINK_BUSINESS_ID);
            productIdIn.add(productId);
        }
        // 获取产品信息
        Map<Long, ProductEntityExt> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (productIdIn.size() >= 1) {
            // 从产品表中获取对应的产品信息
            Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            params.put("corpid", corpid);
            params.put("idIn", productIdIn);
            params.put("del", 0);
            List<ProductEntityExt> productModelEntitys = productModel.findEntitys(params);
            if (productModelEntitys != null) {
                for (ProductEntityExt entity : productModelEntitys) {
                    productMap.put(entity.getId(), entity);
                }
            }
        }
        return productMap;
    }

    @Override
    public SupplierDeleteBatchVO deleteBatch(SupplierDeleteBatchDTO supplierDeleteBatchDTO) throws XbbException {
        SupplierDeleteBatchVO supplierDeleteBatchVO = new SupplierDeleteBatchVO();
        List<String> name= new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> supplierIdIn = supplierDeleteBatchDTO.getDataIdList();
        String corpid = supplierDeleteBatchDTO.getCorpid();
        Set<Long> deletePayBalanceId = new HashSet<>();

        try {
            // TODO 删除权限校验
            // TODO 老板、超管、负责人有删除供应商的权限
            Map<String, Object> param = BeanUtil.convertBean2Map(supplierDeleteBatchDTO, true);
            param.put("idIn", supplierIdIn);
            List<SupplierEntityExt> supplierList = supplierModel.findEntitys(param);
            if (Objects.isNull(supplierList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }

            Set<String> errorTypeSet = new HashSet<>();
            Set<String> errorDataSet = new HashSet<>();
            List<String> errorTypeList = new ArrayList<>(errorTypeSet);
            if (!supplierIdIn.isEmpty()) {
                // 判断该供应商是否存在采购合同，如果存在不允许其删除
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(StringConstant.CORPID+StringConstant.POINT+StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA+StringConstant.POINT+ PurchaseEnum.SUPPLIER_ID.getAttr(), supplierIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                fieldList.add(StringConstant.JSON_DATA+StringConstant.POINT+ PurchaseEnum.SUPPLIER_ID.getAttr());
                List<PaasFormDataEntityExt> purchaseList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                if (Objects.isNull(purchaseList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }

                //供应商对应的联系人进入审批
                Set<Long> hasSupplierContactId = new HashSet<>();
                if (commonHelp.isOpenWorkFlow(corpid)) {
                    // 开启工作流的时候从业务数据主表获取审批中数据
                    boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.filter(termsQuery(SupplierContactEnum.getEsAttr4Keyword(SupplierContactEnum.SUPPLIER_ID), supplierIdIn));
                    boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT.getType()));
                    List<PaasFormDataEntityExt> contactFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT,
                            boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(SupplierContactEnum.getAttrConnectData(SupplierContactEnum.SUPPLIER_ID), FieldTypeEnum.DATAID.getAlias()));
                    contactFormDataList.forEach(item -> {
                        JSONObject data = item.getData();
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(SupplierContactEnum.SUPPLIER_ID.getAttr())) && data.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr()) > 0L) {
                            hasSupplierContactId.add(data.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr()));
                        }
                    });
                } else {
                    List<PaasProcessDataEntity> approvalContactList = paasProcessDataModel.getInApprovalDataByIdCondition(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), SupplierContactEnum.SUPPLIER_ID.getAttr(), supplierIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
                    approvalContactList.forEach((item) -> {
                        JSONObject data = JSONObject.parseObject(item.getData());
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(SupplierContactEnum.SUPPLIER_ID.getAttr())) && data.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr()) > 0L) {
                            hasSupplierContactId.add(data.getLong(SupplierContactEnum.SUPPLIER_ID.getAttr()));
                        }
                    });
                }
                //采购合同
                Set<Long> supplierIdSet = new HashSet<>();
                purchaseList.forEach(item->{
                    JSONObject data = item.getData();
                    if (Objects.nonNull(data) && Objects.nonNull(data.get(PurchaseEnum.SUPPLIER_ID.getAttr()))) {
                        errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PURCHASE_NOT_DEL));
                        supplierIdSet.add(data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr()));
                    }
                });

                if (commonHelp.isOpenWorkFlow(corpid)) {
                    boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.filter(termsQuery(PurchaseEnum.getEsAttr4Keyword(PurchaseEnum.SUPPLIER_ID), supplierIdIn));
                    boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PURCHASE.getType()));
                    List<PaasFormDataEntityExt> purchaseFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PURCHASE,
                            boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PurchaseEnum.getAttrConnectData(PurchaseEnum.SUPPLIER_ID), FieldTypeEnum.DATAID.getAlias()));
                    purchaseFormDataList.forEach(item -> {
                        JSONObject data = item.getData();
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(PurchaseEnum.SUPPLIER_ID.getAttr())) && data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr()) > 0L) {
                            supplierIdSet.add(data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr()));
                        }
                    });
                } else {
                    List<PaasProcessDataEntity> approvalPurchaseList = paasProcessDataModel.getInApprovalDataByIdCondition(XbbRefTypeEnum.PURCHASE.getCode(), PurchaseEnum.SUPPLIER_ID.getAttr(), supplierIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
                    approvalPurchaseList.forEach((item) -> {
                        JSONObject data = JSONObject.parseObject(item.getData());
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(PurchaseEnum.SUPPLIER_ID.getAttr())) && data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr()) > 0L) {
                            supplierIdSet.add(data.getLong(PurchaseEnum.SUPPLIER_ID.getAttr()));
                        }
                    });
                }

                //付款单
                Set<Long> hasPaySheetSupplierId = new HashSet<>();
                if (commonHelp.isOpenWorkFlow(corpid)) {
                    boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.filter(termsQuery(PaySheetEnum.getEsAttr4Keyword(PaySheetEnum.LINK_SUPPLIER), supplierIdIn));
                    boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                    boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET.getType()));
                    List<PaasFormDataEntityExt> paySheetFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET,
                            boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PaySheetEnum.getAttrConnectData(PaySheetEnum.LINK_SUPPLIER), FieldTypeEnum.DATAID.getAlias()));
                    paySheetFormDataList.forEach(item -> {
                        JSONObject data = item.getData();
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(PaySheetEnum.LINK_SUPPLIER.getAttr())) && data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()) > 0L) {
                            hasPaySheetSupplierId.add(data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()));
                        }
                    });
                } else {
                    List<PaasProcessDataEntity> approvalPaySheetList = paasProcessDataModel.getInApprovalDataByIdAndTypeCondition(XbbRefTypeEnum.PAY_SHEET.getCode(), PaySheetEnum.LINK_SUPPLIER.getAttr(), supplierIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
                    approvalPaySheetList.forEach((item) -> {
                        JSONObject data = JSONObject.parseObject(item.getData());
                        if (Objects.nonNull(data) && Objects.nonNull(data.get(PaySheetEnum.LINK_SUPPLIER.getAttr())) && data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()) > 0L) {
                            hasPaySheetSupplierId.add(data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()));
                        }
                    });
                }
                List<PaasFormDataEntityExt> paySheetList = payPlanSheetService.getPaymentSheetEsDataListBySupplierIds(corpid,supplierIdIn,Arrays.asList(PaySheetTypeEnum.RED_PREPAY.getCode(),PaySheetTypeEnum.PREPAY.getCode()));

                paySheetList.forEach((item)->{
                    JSONObject data = item.getData();
                    if (Objects.nonNull(data) && Objects.nonNull(data.get(PaySheetEnum.LINK_SUPPLIER.getAttr())) && data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()) > 0L) {
                        hasPaySheetSupplierId.add(data.getLong(PaySheetEnum.LINK_SUPPLIER.getAttr()));
                    }
                });
                Set<Long> noAllowDeleteSupplierId = new HashSet<>();
                Iterator iterator = supplierList.iterator();
                while (iterator.hasNext()){
                    SupplierEntityExt item = (SupplierEntityExt) iterator.next();
                    JSONObject data = item.getData();
                    Long supplierId = item.getId();
                    if ( supplierIdSet.contains(supplierId) ) {
                        noAllowDeleteSupplierId.add(supplierId);
                        if ( Objects.nonNull(data) && Objects.nonNull(data.get(SupplierEnum.SUPPLIER_NAME.getAttr())) ) {
                            errorDataSet.add(data.getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
                            errorTypeList.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PURCHASE_NOT_DEL));
                        }
                        continue;
                    }
                    if ( hasPaySheetSupplierId.contains(supplierId) ) {
                        noAllowDeleteSupplierId.add(supplierId);
                        if ( Objects.nonNull(data) && Objects.nonNull(data.get(SupplierEnum.SUPPLIER_NAME.getAttr())) ) {
                            errorDataSet.add(data.getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
                            errorTypeList.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PAY_PALN_SHEET_NOT_DEL));
                        }
                        continue;
                    }
                    if ( hasSupplierContactId.contains(supplierId) ) {
                        noAllowDeleteSupplierId.add(supplierId);
                        if ( Objects.nonNull(data) && Objects.nonNull(data.get(SupplierEnum.SUPPLIER_NAME.getAttr())) ) {
                            errorDataSet.add(data.getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
                            errorTypeList.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_SUPPLIER_CONTACT_NOT_DEL));
                        }
                        continue;
                    }
                }
                supplierIdIn.removeAll(noAllowDeleteSupplierId);
            }


            //查询名称
            BoolQueryBuilder builder = boolQuery();
            // 添加corpid,formId,del
            builder.filter(termQuery("corpid.keyword", corpid));
            builder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            builder.filter(termsQuery(StringConstant.DATA_ID, supplierIdIn));
            List<String> nameFieldList = new ArrayList<>();
            nameFieldList.add(SupplierEnum.getAttrConnectData(SupplierEnum.SUPPLIER_NAME));
            List<PaasFormDataEntityExt> nameList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER, builder, PaasFormDataEntityExt.class, nameFieldList);
            for(PaasFormDataEntityExt entityExt : nameList){
                JSONObject data = entityExt.getData();
                String supplierName = FastJsonHelper.getStringOrDefaultFromFormData(data, SupplierEnum.SUPPLIER_NAME.getAttr(), "");
                name.add(supplierName);
            }

            List<String> errorDataList = new ArrayList<>(errorDataSet);
            if(!supplierIdIn.isEmpty()) {
                if(BasicConstant.ONE.equals(supplierDeleteBatchDTO.getSingleFlag())
                        && BasicConstant.ONE.equals(supplierIdIn.size())){
                    supplierModel.deleteByKey(supplierIdIn.get(0),corpid);
                }else {
                    supplierModel.deleteBatch(supplierIdIn, corpid);
                }
                supplierDeleteBatchVO.setDeleteIds(supplierIdIn);
            }
            // 删除供应商负责人
            SupplierUserDeleteBatchDTO supplierUserDeleteBatchDTO = new SupplierUserDeleteBatchDTO();
            BeanUtil.copyProperties(supplierDeleteBatchDTO, supplierUserDeleteBatchDTO);
            supplierUserDeleteBatchDTO.setSupplierIdIn(supplierIdIn);
            supplierUserService.deleteBatch(supplierUserDeleteBatchDTO);
            if (!supplierIdIn.isEmpty()) {
                // 删除供应商联系人
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                boolQueryBuilder.filter(termQuery(StringConstant.CORPID+StringConstant.POINT+StringConstant.KEY_WORD, corpid));
                boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA+StringConstant.POINT+ SupplierContactEnum.SUPPLIER_ID.getAttr(), supplierIdIn));
                List<String> fieldList = new ArrayList<>();
                fieldList.add(StringConstant.DATA_ID);
                List<PaasFormDataEntityExt> supplierContactList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_CONTACT, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
                if (Objects.isNull(supplierContactList)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                List<Long> supplierContactIdIn = new ArrayList<>();
                supplierContactList.forEach((item)->{
                    supplierContactIdIn.add(item.getDataId());
                });
                if(!supplierContactIdIn.isEmpty()) {
                    SupplierContactDeleteBatchDTO supplierContactDeleteBatchDTO = new SupplierContactDeleteBatchDTO();
                    BeanUtil.copyProperties(supplierDeleteBatchDTO, supplierContactDeleteBatchDTO);
                    supplierContactDeleteBatchDTO.setSupplierContactIdIn(supplierContactIdIn);
                    supplierContactService.deleteBatch(supplierContactDeleteBatchDTO);
                }

                // 删除供应商跟进记录
                deleteSupplierCommunicate(supplierDeleteBatchDTO);

                // 更新产品表单数据的供应商字段
                Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                modelMap.put("corpid", supplierDeleteBatchDTO.getCorpid());
                modelMap.put("del", 0);
                modelMap.put("supplierIdIn", supplierIdIn);
                List<SupplierProductEntity> supplierProductList= supplierProductModel.findEntitys(modelMap);
                Set<Long> productIdIn = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                supplierProductList.forEach(supplierProduct -> productIdIn.add(supplierProduct.getProductId()));

                // 根据供应商删除供应商产品信息
                SupplierProductDeleteBatchDTO supplierProductDeleteBatchDTO = new SupplierProductDeleteBatchDTO();
                BeanUtil.copyProperties(supplierDeleteBatchDTO, supplierProductDeleteBatchDTO);
                supplierProductDeleteBatchDTO.setSupplierIdList(supplierIdIn);
                supplierProductService.deleteBySupplierId(supplierProductDeleteBatchDTO);

                if (!productIdIn.isEmpty()) {
                    updateProductLinkSupplier(supplierDeleteBatchDTO.getCorpid(), productIdIn);
                }
                //预收款余额表对应的删除
                BoolQueryBuilder payBalanceQuery = boolQuery();
                payBalanceQuery.filter(termsQuery(PayBalanceEnum.SUPPLIER_ID.getAttr(), supplierIdIn));
                payBalanceQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
                payBalanceQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                List<PayBalanceEntity> payBalanceList = esHelper.findByScroll(IndexTypeEnum.IDX_PAY_BALANCE, payBalanceQuery, PayBalanceEntity.class, Arrays.asList("id",PayBalanceEnum.SUPPLIER_ID.getAttr(),PayBalanceEnum.ADVANCE_PAY_BALANCE.getAttr()));
                //预收款余额等于0,存id
                if(CollectionsUtil.isNotEmpty(payBalanceList)){
                    for (PayBalanceEntity payBalanceEntity : payBalanceList) {
                        deletePayBalanceId.add(payBalanceEntity.getId());
                    }
                }
                deletePayBalance(corpid, new ArrayList<>(deletePayBalanceId));

                PushNotifyDeleteDTO pushNotifyDeleteDTO = new PushNotifyDeleteDTO();
                BeanUtil.copyProperties(supplierDeleteBatchDTO, pushNotifyDeleteDTO);
                pushNotifyDeleteDTO.setNeedDelNotifyIdList(supplierIdIn);
                pushNotifyDeleteDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
                pushNotifyService.deletePushNotify(pushNotifyDeleteDTO);
            }
            supplierDeleteBatchVO.setErrorDataList(errorDataList);
            supplierDeleteBatchVO.setErrorTypeList(errorTypeList);
            supplierDeleteBatchVO.setErrorDataMemo(SaasDeleteHelp.getErrorDataMemo(errorTypeList, errorDataList));

        } catch (Exception e) {
            LOG.error("supplierServiceImpl.deleteBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
        if (Objects.equals(1, supplierDeleteBatchDTO.getIsBusinessRule())) {
            operateTypeEnum = OperateTypeEnum.RULE_DELETE;
        }
        //生成删除日志(区分单个删除和批量删除)
        String userId = supplierDeleteBatchDTO.getUserId();
        String userName = supplierDeleteBatchDTO.getLoginUserName();
        String nameStr = StringUtils.join(name, "，");
        if(supplierIdIn.size() > 1){
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.SUPPLIER.getName(), supplierIdIn.size());
            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            InfoArrPojo infoArrPojo = new InfoArrPojo();
            infoArrPojo.setTitle(SupplierEnum.SUPPLIER_NAME.getAttrName());
            infoArrPojo.setContent(nameStr);
            infoArrPojoList.add(infoArrPojo);
            mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER, operateTypeEnum,
                    "", "", memo, supplierDeleteBatchDTO.getHttpHeader());
        } else if (Objects.equals(supplierIdIn.size(), 1)){
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.SUPPLIER.getName(), nameStr);
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SUPPLIER, operateTypeEnum,
                    supplierIdIn.get(0).toString(), nameStr, memo, supplierDeleteBatchDTO.getHttpHeader());
        }

        return supplierDeleteBatchVO;
    }

    @Override
    public SupplierUpdateBatchVO updateBatch(SupplierUpdateBatchDTO supplierUpdateBatchDTO) throws XbbException {
        SupplierUpdateBatchVO supplierUpdateBatchVO = new SupplierUpdateBatchVO();
        try {
            String corpid = supplierUpdateBatchDTO.getCorpid();
            List<UpdateDataEntity> updateList = new ArrayList<>();
            List<SupplierUpdateDTO> supplierUpdateDTOS = supplierUpdateBatchDTO.getSupplierList();
            if (Objects.nonNull(supplierUpdateDTOS) && !supplierUpdateDTOS.isEmpty()) {
                supplierUpdateDTOS.forEach((item)->{
                    updateList.add(ExplainUtil.getUpdateData(item.getId(), item.getData(), corpid));
                });
            }
            if (!updateList.isEmpty()) {
                supplierModel.updateBatch(updateList, corpid);
            }
        } catch (Exception e) {
            LOG.error("supplierServiceImpl.updateBatch 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return supplierUpdateBatchVO;
    }

/*    @Override
    public BusinessProductListVO getSupplierProductList(BusinessProductListDTO businessProductListDTO, JSONObject dataList) throws XbbException {
        //TODO haibin.zhang 改不动不敢改，除非有明确的文档，可以整个方法推了
        // 获取参数
        BusinessProductListVO businessProductListVO = new BusinessProductListVO();
        String corpid = businessProductListDTO.getCorpid();
        String userId = businessProductListDTO.getUserId();
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        Integer businessType = businessProductListDTO.getBusinessType();
        Boolean detailGet = businessProductListDTO.getDetailGet();
        Long supplierId = businessProductListDTO.getDataId();
        List<SupplierProductEntity> supplierProducts = new ArrayList<>();
        // 获取关联产品
//        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        modelMap.put(ParameterConstant.CORPID, corpid);
//        modelMap.put("supplierId", supplierId);
//        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
//        modelMap.put(ParameterConstant.PAGE, businessProductListDTO.getPage());
//        PageHelper pageHelper = PageHelperUtil.getPageHelper(modelMap, supplierProductModel, businessProductListDTO.getPageSize());
//        List<SupplierProductEntity> supplierProducts = (List<SupplierProductEntity>) PageHelperUtil.getEntityList(modelMap, pageHelper, supplierProductModel);
//        List<SupplierProductEntity> supplierProducts = new ArrayList<>();
        if (businessProductListDTO.getForProcess()) {
            JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(saasUpdateHelp.getJsonObjectOrDefaultFromFormData(dataList, SupplierEnum.PRODUCT_LIST.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
            Map<Long,ProductEntityExt> productMap = getProductMap(corpid ,productArr);
//            pageHelper= PageHelperUtil.initPageHelper(productMap.size(),businessProductListDTO.getPage(),businessProductListDTO.getPageSize());
            getProductList(supplierProducts,productArr,productMap);

        } else {
            Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
            modelMap.put(ParameterConstant.PAGE, businessProductListDTO.getPage());
            modelMap.put(ParameterConstant.CORPID, corpid);
            modelMap.put("supplierId", supplierId);
            PageHelper pageHelper = PageHelperUtil.getPageHelper(modelMap, supplierProductModel, businessProductListDTO.getPageSize());
            businessProductListVO.setPageHelper(pageHelper);
            supplierProducts = (List<SupplierProductEntity>) PageHelperUtil.getEntityList(modelMap, pageHelper, supplierProductModel);
        }

        Map<Long, SupplierProductEntity> supplierProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        supplierProducts.forEach(item -> supplierProductMap.put(item.getProductId(), item));

        // 用于存放当前启用的产品模板解释的map
        Map<String, FieldAttrEntity> nowProductExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        saasAddHelp.getRelativeProductExplainsFromDB(corpid, nowProductExplainMap, null);

        Set<Long> productIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productIds.add(-1L);
        supplierProducts.forEach(item -> productIds.add(item.getProductId()));
*//*
        // 根据productIdIn获取对应产品信息，需要分页信息，从es中获取
        EsDataDTO esDataDTO = new EsDataDTO();
        esDataDTO.setCorpid(corpid);
        esDataDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        esDataDTO.setFieldList(null);
        esDataDTO.setDel(0);
        List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);*//*
        // idIn
//        List<Object> idIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//        productIds.forEach(item -> idIn.add(item));
        // 根据productIdIn获取对应产品信息
        List<PaasFormDataEntityExt> paasFormDataESList = productService.getProductListById(productIds, corpid, DelEnum.NORMAL);

        // 返回给前端的接受对象
        JSONObject productFinalObj = new JSONObject();
        JSONArray productArray = new JSONArray();
        Map<Integer, JSONObject> productSortMap = new TreeMap<>();
//        BusinessProductListVO businessProductListVO = new BusinessProductListVO();
        // 与productList同级，返回对应关联产品的attr
        String attrStr = "";

        for (PaasFormDataEntityExt product : paasFormDataESList) {
            Long parentProductId = product.getDataId();
            SupplierProductEntity supplierProduct = supplierProductMap.get(parentProductId);
            if (supplierProduct == null) {
                continue;
            }
            JSONObject productData = product.getData();
            StringBuilder spec = new StringBuilder();

            ChildProductDTO childProductDTO = new ChildProductDTO();
            childProductDTO.setCorpid(corpid);
            childProductDTO.setParentProductId(Arrays.asList(parentProductId));
            PaasFormDataEsListVO childProductEsDataList = productService.getChildProductList(childProductDTO);
            List<PaasFormDataEntityExt> childProduct = childProductEsDataList.getPaasFormDataESList();
            for (PaasFormDataEntityExt productEntity : childProduct) {
                JSONObject childDataList = productEntity.getData();
                String specification = childDataList.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                if (spec.length() > 0) {
                    spec.append(",").append(specificationModel.joinSpecification(specification));
                } else {
                    spec.append(specificationModel.joinSpecification(specification));
                }
            }
            // 价格和成本区间
            String priceStr = "";
            String costStr = "";
            if (childProduct.size() >= 1) {
                FieldAttrEntity priceField = nowProductExplainMap.getOrDefault(ProductEnum.PRICE.getSaasAttr(), new FieldAttrEntity());
                FieldAttrEntity costField = nowProductExplainMap.getOrDefault(ProductEnum.COST.getSaasAttr(), new FieldAttrEntity());
                priceStr = productService.getPriceOrCostRegion(childProduct, ProductEnum.PRICE.getAttr(), priceField.getAccuracy());
                costStr = productService.getPriceOrCostRegion(childProduct, ProductEnum.COST.getAttr(), costField.getAccuracy());
            }

            FormatRelativeProductEntityExt formatProduct = new FormatRelativeProductEntityExt();
            formatProduct.setRefId(supplierProduct.getSupplierId());
            formatProduct.setProductId( supplierProduct.getProductId());
            formatProduct.setProductName(saasUpdateHelp.getStringOrDefaultFromFormData(productData, ProductEnum.NAME.getAttr(), ""));
            formatProduct.setProductNo(saasUpdateHelp.getStringOrDefaultFromFormData(productData, ProductEnum.PRODUCT_NO.getAttr(), ""));
            formatProduct.setProductSpecification(spec.toString());
            formatProduct.setProductUnit(saasUpdateHelp.getStringOrDefaultFromFormData(productData, ProductEnum.UNIT.getAttr(), ""));
            formatProduct.setProductPriceStr(priceStr);
            formatProduct.setCostStr(costStr);
            JSONArray imageUrlArray = saasUpdateHelp.getJsonArrFromFormData(productData,ProductEnum.PRODUCT_IMGS.getAttr());
            if (Objects.nonNull(imageUrlArray) && !imageUrlArray.isEmpty()) {
                formatProduct.setImageUrl(imageUrlArray.getString(imageUrlArray.size() - 1));
            }

            FormatRelativeProductDTO formatRelativeProductDTO = new FormatRelativeProductDTO();
            BeanUtil.copyProperties(businessProductListDTO, formatRelativeProductDTO);
            formatRelativeProductDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER.getCode());
            formatRelativeProductDTO.setTargetBusinessType(businessType);
            formatRelativeProductDTO.setCorpid(corpid);
            formatRelativeProductDTO.setNowProductExplainMap(nowProductExplainMap);
            formatRelativeProductDTO.setFormatRelativeProductEntityExt(formatProduct);
            formatRelativeProductDTO.setUserEntity(userEntity);

            JSONObject productObj = productService.getFormatProductJsonArray(formatRelativeProductDTO);
            productArray.add(productObj);
        }
        productFinalObj.put(StringConstant.PRODUCT_LIST, productArray);
        if (detailGet) {
            productFinalObj.put(BusinessConstant.EXPLAINS, saasGetHelp.getSelectProductExplains(XbbRefTypeEnum.SUPPLIER, businessProductListDTO.getBusinessType(), corpid, PurchaseEnum.PRODUCT.getAttr()));
        }
        productFinalObj.put(StringConstant.REDUNDANT_FIELD_ATTR_BEGIN_FLAG, attrStr);
        businessProductListVO.setProduct(productFinalObj);
//        businessProductListVO.setPageHelper(pageHelper);
        return businessProductListVO;
    }*/

    @Override
    public void batchEditAttr(SupplierEditAttrUpdateDTO supplierEditAttrUpdateDTO) throws XbbException {
        List<Long> idIn = supplierEditAttrUpdateDTO.getDataIdList();
        try {
            String corpid = supplierEditAttrUpdateDTO.getCorpid();
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("idIn", idIn);
            param.put("del", 0);
            List<SupplierEntityExt> supplierList  = supplierModel.findEntitys(param);
            if (Objects.isNull(supplierList)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            //权限团队校验前置了
            List<Long> errorIdList = new ArrayList<>();
//            List<Long> errorIdList = userTeamHelp.batchTeamMembersCheckEditPermission(supplierEditAttrUpdateDTO.getBusinessType(), supplierEditAttrUpdateDTO.getSaasMark(),
//                    supplierEditAttrUpdateDTO.getMenuId(), supplierEditAttrUpdateDTO.getLoginUser(), supplierEditAttrUpdateDTO.getDistributorMark(),
//                    supplierEditAttrUpdateDTO.getDataIdList(), new HashMap<>());
            List<String> errorNameList = new ArrayList<>();
            for (SupplierEntityExt supplierEntityExt : supplierList) {
                if (errorIdList.contains(supplierEntityExt.getId())) {
                    errorNameList.add(supplierEntityExt.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
                }
            }
            String nameStr = org.apache.commons.lang.StringUtils.join(errorNameList, "、");
            if (CollectionUtils.isNotEmpty(errorNameList)) {
                throw new XbbException(UserTeamErrorCodeEnum.API_ERROR_271038.getCode(), String.format(UserTeamErrorCodeEnum.API_ERROR_271038.getMsg(), nameStr));
            }

            // 审批通过后是否允许编辑
            Map<Long, Boolean> editAfterFinishedMap = paasProcessTemplateModel.getEditAfterFinishedMap(corpid, supplierEditAttrUpdateDTO.getAppId(), supplierEditAttrUpdateDTO.getMenuId(), supplierEditAttrUpdateDTO.getLoginUser());
            List<PaasFormDataEntityExt> dataList = new ArrayList<>();
            BeanUtil.copyPropertiesList(supplierList,dataList,PaasFormDataEntityExt.class);
            // 审批后能否编辑
            paasProcessTemplateModel.checkEditAfterFinished(editAfterFinishedMap, dataList);

            List<SupplierUpdateDTO> supplierUpdateDTOS = new ArrayList<>();
            idIn.forEach((item)->{
                SupplierUpdateDTO supplierUpdateDTO = new SupplierUpdateDTO();
                supplierUpdateDTO.setId(item);
                JSONObject data = ProSaveHelp.getBatchUpdateData(supplierEditAttrUpdateDTO.getFieldEditedList());
                supplierUpdateDTO.setData(data);
                supplierUpdateDTOS.add(supplierUpdateDTO);
            });
            if (!supplierUpdateDTOS.isEmpty()) {
                SupplierUpdateBatchDTO supplierUpdateBatchDTO = new SupplierUpdateBatchDTO();
                BeanUtil.copyProperties(supplierEditAttrUpdateDTO, supplierUpdateBatchDTO);
                supplierUpdateBatchDTO.setSupplierList(supplierUpdateDTOS);
                updateBatch(supplierUpdateBatchDTO);
            }
            // 批量编辑日志
            List<String> updataItemList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<Long> dataIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for (SupplierEntityExt item : supplierList) {
                dataIdList.add(item.getId());
                JSONObject data = item.getData();
                String serialNo = item.getSerialNo();
                String opObjectName = data.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
                StringBuilder sb = new StringBuilder();
                opObjectName = opObjectName == null ? serialNo : sb.append(serialNo).append("（").append(opObjectName).append("）").toString();
                updataItemList.add(opObjectName);
            }
            String updataItem = StringUtils.join(updataItemList, "，");
            String userId = supplierEditAttrUpdateDTO.getUserId();
            String loginUserName = supplierEditAttrUpdateDTO.getLoginUserName();
            // 标签特殊处理
            Integer fieldType = supplierEditAttrUpdateDTO.getFieldType();
            logHelp.analysisLabel(corpid, fieldType, supplierEditAttrUpdateDTO.getIsFieldDependence(), supplierEditAttrUpdateDTO.getLogFieldEditedList());

            String changedLogItemsStr = logHandleHelp.getChangedLogItemsStr(supplierEditAttrUpdateDTO.getLogFieldEditedList());
            if(dataIdList.size() > 1 ){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_BATCH_ATTR), loginUserName, XbbRefTypeEnum.SUPPLIER.getName(),
                        changedLogItemsStr, dataIdList.size());
                List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                InfoArrPojo infoArrPojo = new InfoArrPojo();
                infoArrPojo.setTitle(XbbRefTypeEnum.SUPPLIER.getName());
                infoArrPojo.setContent(updataItem);
                infoArrPojoList.add(infoArrPojo);
                mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, loginUserName, OperateModuleTypeEnum.SUPPLIER, OperateTypeEnum.EDIT,
                        "", "", memo, supplierEditAttrUpdateDTO.getHttpHeader());
            } else if (Objects.equals(dataIdList.size(), 1)){
                String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_ATTR), loginUserName, XbbRefTypeEnum.SUPPLIER.getName(), updataItem,
                        changedLogItemsStr);
                mongoLogHelp.buildLog(corpid, userId, loginUserName, OperateModuleTypeEnum.SUPPLIER, OperateTypeEnum.EDIT,
                        dataIdList.get(0).toString(), updataItem, memo, supplierEditAttrUpdateDTO.getHttpHeader());
            }
        }catch (XbbException e) {
            throw e;
        }  catch (Exception e) {
            LOG.error("supplierServiceImpl.batchEditAttr 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    /**
     * 星级：将数字转成文字显示
     *
     * @param level 星级
     * @author GuoJun.HU
     * @since V1.0
     * @return String
     * @date 2019/3/22 10:15
     */
    @Override
    public String getLevelString(String level) {
        return LevelUtil.getLevelString(level);
    }

    @Override
    public String transferLevel2Chinese(Integer star) {
        return LevelUtil.transferLevel2Chinese(star);
    }

    @Override
    public FormDataAddDTO formatExcelValue(ImportFormDataDTO importFormDataDTO, List<CellTitlePojo> titlePojoList, RowGroupPojo rowGroupPojo, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(importFormDataDTO, formDataAddDTO);
        JSONObject dataJson = new JSONObject();
        List<List<CellValuePojo>> rowValueList = rowGroupPojo.getRowValueList();
        // 分组的第一条数据作为给实体对象赋值的数据
        List<CellValuePojo> cellValueList = rowValueList.get(0);
        String corpid = importFormDataDTO.getCorpid();
        //存放产品ID 的set
        Set productIdSet = new HashSet();
        for (FieldAttrEntityForImport fieldAttr : fieldAttrList) {
            String attr = fieldAttr.getAttr();
            Integer fieldType = fieldAttr.getFieldType();
            String attrName = fieldAttr.getAttrName();
            Integer columnIndex = importHelper.getColumnIndexByTitle(titlePojoList, attrName, null);
            Object cellValue = importHelper.getValueByColumnIndex(cellValueList, columnIndex);
            if (Objects.equals(attr, SupplierEnum.PRODUCT_LIST.getAttr())) {
                importHelper.formatCommonProduct(titlePojoList, dataJson, rowValueList, fieldAttr, XbbRefTypeEnum.SUPPLIER.getCode(), corpid);
                JSONArray productJsonArray = dataJson.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
                for (int i = 0; i < productJsonArray.size(); i++) {
                    productIdSet.add(productJsonArray.getJSONObject(i).get(ProductEnum.NAME.getAttr()));
                }
                if (productIdSet.size() < productJsonArray.size()){
                    throw new XbbException(InstockErrorCodeEnum.API_ERROR_210044);
                }
            } else if (Objects.equals(fieldType, FieldTypeEnum.SUB_FORM.getType())) {
                importHelper.formatSubFormValue4Import(rowValueList, titlePojoList, importFormDataDTO, fieldAttr, dataJson);
            } else {
                if (Objects.isNull(cellValue) || StringUtil.isEmpty(cellValue.toString())) {
                    continue;
                }
                if (ImportHelper.commonHandleFieldType.contains(fieldType)) {
                    importHelper.formatCommonField(dataJson, fieldAttr, cellValue);
                } else if (Objects.equals(fieldType, FieldTypeEnum.SERIALNO.getType())) {
                    formDataAddDTO.setSerialNo(cellValue.toString());
                }else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA.getType())){
                    importHelper.formatLinkData(cellValue, fieldAttr, dataJson);
                } else if (Objects.equals(fieldType, FieldTypeEnum.LINK_DATA_MULTI.getType())) {
                    importHelper.formatLinkDataMulti(cellValue, importFormDataDTO, fieldAttr, dataJson);
                } else {
                    dataJson.put(attr, cellValue);
                }
            }
        }
        if (formDataAddDTO.getSerialNo() == null) {
            formDataAddDTO.setSerialNo("");
        }
        formDataAddDTO.setDataList(dataJson);
        return formDataAddDTO;
    }

    @Override
    public void formatExportValue(List<PaasFormDataEntityExt> paasFormDataESList, FormDataListDTO formDataListDTO, List<FieldAttrEntityForImport> fieldAttrList) throws XbbException {
        // 所有产品
        Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        params.put(ParameterConstant.CORPID, formDataListDTO.getCorpid());
        params.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<ProductEntityExt> productList = productModel.findEntitys(params);
        Map<Long, ProductEntityExt> productMap = new HashMap<>();
        productList.forEach(item -> productMap.put(item.getId(), item));
        Set<Long> supplierSet = new HashSet<>();
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            supplierSet.add(paasFormDataEntityExt.getId());
        }
        params.put("supplierIdIn", supplierSet);
        params.put("orderByStr","sort");
        List<SupplierProductEntity> supplierProductEntities = supplierProductModel.findEntitys(params);
        Map<Long, List<SupplierProductEntity>> supplierProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        supplierProductEntities.forEach(item -> {
            if (supplierProductMap.containsKey(item.getSupplierId())) {
                supplierProductMap.get(item.getSupplierId()).add(item);
            } else {
                List<SupplierProductEntity> supplierProductList = new ArrayList<>();
                supplierProductList.add(item);
                supplierProductMap.put(item.getSupplierId(), supplierProductList);
            }
        });

        Map<String, MultiUnitItemPoJo> groupBaseUnitStringMap = relativeProductHelp.getGroupBaseUnitStringMap(formDataListDTO.getCorpid());

        // 暂时只处理产品
        for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
            Long supplierId = paasFormDataEntityExt.getId();
            JSONObject formDataObj = paasFormDataEntityExt.getData();
            if (supplierProductMap.containsKey(supplierId)) {
                List<SupplierProductEntity> supplierProductList = supplierProductMap.get(supplierId);
                JSONArray productArray = new JSONArray();
                for (SupplierProductEntity entity : supplierProductList) {
                    if (productMap.containsKey(entity.getProductId())) {
                        JSONObject productItemObj = entity.getData() == null ? new JSONObject() : entity.getData();;
                        JSONObject productData =  productMap.get(entity.getProductId()).getData();
                        productItemObj.put(SelectProductEnum.PRODUCT_NAME.getAttr(), productData.get(ProductEnum.NAME.getAttr()));
                        productItemObj.put(SelectProductEnum.BARCODE.getAttr(), productData.get(ProductEnum.BARCODE.getAttr()));
                        productItemObj.put(SelectProductEnum.PRODUCT_NO.getAttr(), productMap.get(entity.getProductId()).getSerialNo());
                        String productSpecification = Objects.equals(productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()), "{}") ? "" : productData.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                        productItemObj.put(SelectProductEnum.SPECIFICATION.getAttr(), productSpecification);
                        productItemObj.put(SelectProductEnum.UNIT.getAttr(), productData.get(ProductEnum.UNIT.getAttr()));
                        productItemObj.put(ProductEnum.ENABLE_MULTI_UNIT.getAttr(), productData.getIntValue(ProductEnum.ENABLE_MULTI_UNIT.getAttr()));
                        if (Objects.equals(productItemObj.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), BasicConstant.ONE)){
                            productItemObj.put(ProductEnum.UNIT.getAttr(), groupBaseUnitStringMap.getOrDefault(productItemObj.getString(ProductEnum.UNIT.getAttr()), new MultiUnitItemPoJo()).getBaseValue());
                            entity.setUnit(productItemObj.getString(ProductEnum.UNIT.getAttr()));
                        }
                        productArray.add(productItemObj);
                    }
                }
                formDataObj.put(SupplierEnum.PRODUCT_LIST.getAttr(), productArray);
            }
        }
    }

    @Override
    public void updateBatchByBusinessRule(SupplierUpdateByBusinessRuleDTO supplierUpdateByBusinessRuleDTO) throws XbbException {
        try {
            String corpid = supplierUpdateByBusinessRuleDTO.getCorpid();
            List<PaasFormDataEntityExt> formDataList = supplierUpdateByBusinessRuleDTO.getFormDataList();
            List<UpdateDataEntity> updateList = ExplainUtil.getUpdateValueByBusinessRule(supplierUpdateByBusinessRuleDTO.getFormDataList(), corpid, supplierUpdateByBusinessRuleDTO.getOperations());

            if (!updateList.isEmpty()) {
                supplierModel.updateBatch(updateList, corpid);
                RuleBusinessLogDTO businessLogDTO = new RuleBusinessLogDTO();
                BeanUtil.copyProperties(supplierUpdateByBusinessRuleDTO, businessLogDTO);
                businessLogDTO.setFormDataList(formDataList);
                ruleBusinessLogger.writeLog(businessLogDTO, updateList);
            }
        } catch (Exception e) {
            LOG.error("purchaseService.updateFormDataByBusinessRule根据业务规则更新数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public ProductSummaryVO summaryProductList(BusinessProductListDTO businessProductListDTO) throws XbbException {
        // 获取参数
        String corpid = businessProductListDTO.getCorpid();
        Long dataId = businessProductListDTO.getDataId();

        // 获取关联产品
        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        modelMap.put(ParameterConstant.CORPID, corpid);
        modelMap.put("supplierId", dataId);
        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        modelMap.put("columns", "product_id");
        modelMap.put("parentIdNot",0);
        List<SupplierProductEntity> supplierProducts = supplierProductModel.findEntitys(modelMap);
        Map<Long, SupplierProductEntity> supplierProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        supplierProducts.forEach(item -> supplierProductMap.put(item.getProductId(), item));

        Set<Long> productIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productIds.add(-1L);
        supplierProducts.forEach(item -> productIds.add(item.getProductId()));

        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery("dataId",productIds));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        Long count = xbbElasticsearchRestTemplate.count(searchRequest, PaasFormDataEntityExt.class);

        ProductSummaryVO businessProductListVO = new ProductSummaryVO();
        Long productSize = count == null ? 0 : count;
        String summaryInfo = productSize + I18nMessageUtil.getMessage(I18nStringConstant.COMMODITY);
        businessProductListVO.setSummaryInfo(summaryInfo);
        return businessProductListVO;
    }

    /**
     * 供应商编辑格式化数据格式
     *
     * @param saasFormSaveDTO 保存的负责人信息
     * @author Jian.Wang
     * @date 2019/1/30 17:33
     * @since v1.0
     **/
    private void saveSupplierUser(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        String corpid = saasFormSaveDTO.getCorpid();
        String userId =saasFormSaveDTO.getUserId();

        SupplierUserEntity supplierUserEntity = new SupplierUserEntity();
        supplierUserEntity.setCorpid(corpid);
        supplierUserEntity.setUserId(userId);
        supplierUserEntity.setDataId(newPaasFormDataEntity.getId());
        supplierUserEntity.setIsMain(1);
        supplierUserEntity.setDistributionTime(DateTimeUtil.getInt());
        UserEntity userEntity = userModel.getByKey(userId, corpid);
        if (Objects.isNull(userEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100004);
        } else {
            supplierUserEntity.setUserName(userEntity.getName());
        }
        supplierUserService.insert(supplierUserEntity);
    }

    /**
     * 删除供应商联系人
     * @param supplierDeleteBatchDTO
     * @throws XbbException
     */
    private void deleteSupplierCommunicate(SupplierDeleteBatchDTO supplierDeleteBatchDTO) throws XbbException {
        // 删除供应商联系人
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery(StringConstant.CORPID+StringConstant.POINT+StringConstant.KEY_WORD, supplierDeleteBatchDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termsQuery(StringConstant.JSON_DATA+StringConstant.POINT+ SupplierCommunicateEnum.SUPPLIER_ID.getAttr(), supplierDeleteBatchDTO.getDataIdList()));
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.DATA_ID);
        List<PaasFormDataEntityExt> list = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_SUPPLIER_COMMUNICATE, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList);
        if (Objects.isNull(list)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        List<Long> supplierCommunicateIdIn = new ArrayList<>();
        list.forEach((item)->{
            supplierCommunicateIdIn.add(item.getDataId());
        });
        if(!supplierCommunicateIdIn.isEmpty()) {
            SupplierCommunicateDeleteBatchDTO supplierCommunicateDeleteBatchDTO = new SupplierCommunicateDeleteBatchDTO();
            BeanUtil.copyProperties(supplierDeleteBatchDTO, supplierCommunicateDeleteBatchDTO);
            supplierCommunicateDeleteBatchDTO.setDataIdList(supplierCommunicateIdIn);
            supplierCommunicateService.deleteBatch(supplierCommunicateDeleteBatchDTO);
        }
    }

    @Override
    public PagingProductVO getPagingProduct(PagingProductDTO pagingProductDTO) throws XbbException {
        PagingProductVO pagingProductVO = new PagingProductVO();
        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        modelMap.put(ParameterConstant.CORPID, pagingProductDTO.getCorpid());
        modelMap.put(ParameterConstant.SUPPLIER_ID, pagingProductDTO.getDataId());
        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        modelMap.put(ParameterConstant.PAGE,  pagingProductDTO.getPage());
        modelMap.put(ParameterConstant.ORDER_BY_STR, BasicConstant.SORT);

        //根据前端传递的conditions获取商品id集合  封装到modelMap中
        List<ConditionsEntityExt> conditionList = pagingProductDTO.getConditions();
        if(CollectionUtils.isNotEmpty(conditionList)){
            List<Object> values = conditionList.get(0).getValue();
            modelMap.put("productIdIn",values);
        }
        modelMap.put("parentIdNot",0);
        PageHelper pageHelper = PageHelperUtil.getPageHelper(modelMap, supplierProductModel, pagingProductDTO.getPageSize());
        List<SupplierProductEntity> supplierProductEntityList = (List<SupplierProductEntity>) PageHelperUtil.getEntityList(modelMap, pageHelper, supplierProductModel);
        if (pagingProductDTO.getUpdateDataTypeEnum().isDetail()) {
            DetailProductVO detailProductVO = formatProduct4DetailShow(supplierProductEntityList, pagingProductDTO);
            pagingProductVO.setProductDataArr(detailProductVO.getProductDataArr());
        }
        pagingProductVO.setPageHelper(pageHelper);
        // 供货产品首列添加删除按钮
        JSONObject option = new JSONObject();
        ButtonPojo buttonPojo = new ButtonPojo();
        buttonPojo.setAttr(SaasButtonEnum.DEL.getAttr());
        buttonPojo.setValue(SaasButtonEnum.DEL.getValue());
        buttonPojo.setDisabled(0);
        option.put("value", Collections.singleton(buttonPojo));
        JSONArray productDataArr = pagingProductVO.getProductDataArr();
        for (int i = 0; i < productDataArr.size(); i++) {
            JSONObject itemData = productDataArr.getJSONObject(i);
            itemData.put(ListOptionEnum.OPTION.getAttr(), option);
        }
        return pagingProductVO;
    }

    @Override
    public void validateProductData(ValidateDataDTO validateDataDTO) throws XbbException {
        JSONObject data = validateDataDTO.getData();
        Map<String, FieldAttrEntity> explainMap = validateDataDTO.getExplainMap();
        FieldAttrEntity linkProductField = explainMap.get(SupplierEnum.PRODUCT_LIST.getAttr());

        JSONArray jsonArray = data.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        Map<String, FieldAttrEntity> subExplainMap = ExplainUtil.getExplainMapByList(linkProductField.getSubForm().getItems());
        // 校验子表单的必填
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        if (Objects.isNull(validateDataDTO.getCreatorId())) {
            handlerExplainDTO.setCreatorId(validateDataDTO.getUserId());
        } else {
            handlerExplainDTO.setCreatorId(validateDataDTO.getCreatorId());
        }
        handlerExplainDTO.setUserId(validateDataDTO.getUserId());
        handlerExplainDTO.setLoginUser(validateDataDTO.getLoginUser());
        FormDataValidateDataHelp.validateRequire(jsonArray, linkProductField, subExplainMap, handlerExplainDTO);

        for (int i = 0;i < jsonArray.size();i++) {
            ValidateDataDTO subValidateData = new ValidateDataDTO();
            BeanUtil.copyProperties(validateDataDTO, subValidateData);
            JSONObject subData = jsonArray.getJSONObject(i);
            subValidateData.setData(subData);
            subValidateData.setExplainMap(subExplainMap);
            for (Map.Entry<String,FieldAttrEntity> entityEntry : subExplainMap.entrySet()){
                FieldAttrEntity subFieldAttrEntity = entityEntry.getValue();
                String attr = entityEntry.getKey();
                if (Objects.equals(subFieldAttrEntity.getIsRedundant(), BasicConstant.ONE)) {
                    formDataValidateDataHelp.validateSubFormData(attr, subValidateData, linkProductField);
                }
            }
            if (!subData.containsKey(SelectProductEnum.MEMO.getAttr())) {
                subData.put(SelectProductEnum.MEMO.getAttr(), "");
            }
        }
    }

    @Override
    public void addSupplierProduct(SupplierProductAddDTO supplierProductAddDTO, SupplierEntityExt supplierEntityExt) throws XbbException {
        String corpid = supplierProductAddDTO.getCorpid();
        Long supplierId = supplierProductAddDTO.getDataId();
        JSONObject data = supplierProductAddDTO.getData();
        JSONArray productArray = data.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        String supplierName = supplierEntityExt.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr());

        if (productArray.isEmpty()) {
            return;
        }
        HashMap<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put("supplierId", supplierId);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        Integer count = supplierProductModel.getEntitysCount(param);

        Set<Long> newProductIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (int i = 0; i < productArray.size();i++) {
            JSONObject jsonObject = productArray.getJSONObject(i);
            Long productId = jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr());
            newProductIds.add(productId);
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, newProductIds));
        // 设置join_field
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        searchSourceBuilder.query(boolQueryBuilder);
        List<String> fieldList = new ArrayList<>();
        fieldList.add(StringConstant.SAAS_LINK_BUSINESS_ID);
        fieldList.add(ProductEnum.PARENT_ID.getAttr());
        fieldList.add(ProductEnum.UNIT.getAttr());
        fieldList.add(ProductEnum.SUPPLIER.getAttr());
        fieldList.add(ProductEnum.SUPPLIER_LINK_TEXT.getAttr());
        fieldList.add(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
        List<PaasFormDataEntityExt> productList = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldList, BasicConstant.ONE, newProductIds.size());
        Map<Long, PaasFormDataEntity> productMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> parentProductIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        productList.forEach(product -> {
            productMap.put(product.getId(), product);
            parentProductIdSet.add(product.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
        });
        boolQueryBuilder = boolQuery();
        searchSourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery(StringConstant.DATA_ID, parentProductIdSet));
        // 设置join_field
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        searchSourceBuilder.query(boolQueryBuilder);
        List<PaasFormDataEntityExt> parentProductList = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PRODUCT, fieldList, 1, parentProductIdSet.size());
        Map<Long, PaasFormDataEntity> parentProductMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        parentProductList.forEach(paasFormDataEntity -> parentProductMap.put(paasFormDataEntity.getId(), paasFormDataEntity));

        List<SupplierProductEntity> addBatchList = new ArrayList<>();
        Integer sort = count;
        SupplierProductEntity supplierProductEntity;
        for (int i = 0;i < productArray.size();i++) {
            JSONObject jsonObject = productArray.getJSONObject(i);
            Long productId = jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr());
            if (newProductIds.contains(productId)) {
                PaasFormDataEntity paasFormDataEntity = productMap.get(productId);
                supplierProductEntity = new SupplierProductEntity(corpid, supplierId, supplierName, paasFormDataEntity.getData().getLong(ProductEnum.PARENT_ID.getAttr()), productId, sort);
                Integer enableMultiUnit = paasFormDataEntity.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr());
                if (Objects.equals(enableMultiUnit, 1)) {
                    jsonObject.remove(ProductConstant.UNIT_RATE);
                    jsonObject.remove(ProductConstant.TRANSFORM_UNIT_RATE);
                    supplierProductEntity.setUnit(jsonObject.getString(SelectProductEnum.UNIT.getAttr()));
                } else {
                    supplierProductEntity.setUnit(paasFormDataEntity.getData().getString(ProductEnum.UNIT.getAttr()));
                    jsonObject.put(SupplierProductEnum.UNIT.getAttr(), paasFormDataEntity.getData().getString(ProductEnum.UNIT.getAttr()));
                }
                supplierProductEntity.setData(jsonObject);
                addBatchList.add(supplierProductEntity);
                sort++;
            }
        }
        if (!addBatchList.isEmpty()) {
            supplierProductModel.batchInsert(addBatchList);
        }
        // 更新产品表里的关联供应商字段
        List<UpdateDataEntity> updateDataEntityList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : productList) {
            PaasFormDataEntity parentProduct = parentProductMap.get(paasFormDataEntity.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
            List<String> supplierIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntity.getData(), ProductEnum.SUPPLIER.getAttr(), new JSONArray()).toJavaList(String.class);
            List<String> supplierNameArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(paasFormDataEntity.getData(), ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), new JSONArray()).toJavaList(String.class);
            List<String> parentSupplierIdArr = null;
            List<String> parentSupplierNameArr = null;
            if (Objects.nonNull(parentProduct)) {
                parentSupplierIdArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(parentProduct.getData(), ProductEnum.SUPPLIER.getAttr(), new JSONArray()).toJavaList(String.class);
                parentSupplierNameArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(parentProduct.getData(), ProductEnum.SUPPLIER_LINK_TEXT.getAttr(), new JSONArray()).toJavaList(String.class);
            }
            if (newProductIds.contains(paasFormDataEntity.getId())) {
                setProductSupplier(corpid, supplierId, supplierName, updateDataEntityList, paasFormDataEntity, supplierIdArr, supplierNameArr);
                if (Objects.nonNull(parentProduct)) {
                    setProductSupplier(corpid, supplierId, supplierName, updateDataEntityList, parentProduct, parentSupplierIdArr, parentSupplierNameArr);
                }
            }
        }
        if (CollectionUtils.isNotEmpty(updateDataEntityList)) {
            productModel.updateBatch(updateDataEntityList, corpid);
        }
    }

    @Override
    public Boolean verifyEditPermissions(DetailTabDataGetDTO detailTabDataGetDTO) throws XbbException {
        Integer saasMark = detailTabDataGetDTO.getSaasMark();
        UserVO userVO = detailTabDataGetDTO.getLoginUser();
        String corpid = detailTabDataGetDTO.getCorpid();
        Integer businessType = detailTabDataGetDTO.getBusinessType();

        Boolean havePermission = true;
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, corpid);
        if (Objects.isNull(paasFormExplainEntity)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
            UpdateProPermissionAliasEnum updateProPermissionAliasEnum = UpdateProPermissionAliasEnum.getByCode(businessType);
            if (Objects.nonNull(updateProPermissionAliasEnum)) {
                if (!userVO.getPermSet().contains(updateProPermissionAliasEnum.getAlias())) {
                    havePermission = false;
                }
            }
        } else {
            Set<Long> idSet = ProPermissionHelp.getPaasEditMenuIdSet(userVO.getPaasPermissions());
            if (!userVO.isAdminOrBoss() && !idSet.contains(paasFormExplainEntity.getMenuId())) {
                havePermission = false;
            }
        }
        if (!havePermission) {
            return havePermission;
        }
        // 校验关联产品字段的编辑权限
        List<SupplierUserEntity> supplierUserEntities = supplierUserModel.getSupplierUserListBySupplierId(corpid, detailTabDataGetDTO.getDataId());
        List<String> ownerId = new ArrayList<>();
        List<String> coUserId = new ArrayList<>();
        supplierUserEntities.forEach((item -> {
            if (BasicConstant.ONE.equals(item.getIsMain())) {
                ownerId.add(item.getUserId());
            } else {
                coUserId.add(item.getUserId());
            }
        }));

        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), SupplierEnum.PRODUCT_LIST.getAttr());
        FieldAttrEntity linkProductField = explainMap.get(SupplierEnum.PRODUCT_LIST.getAttr());
        // 供应商数据
        SupplierEntityExt supplierEntityExt = supplierModel.getByKey(detailTabDataGetDTO.getDataId(), corpid);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setCoUserId(coUserId);
        handlerExplainDTO.setOwnerId(ownerId);
        handlerExplainDTO.setCreatorId(supplierEntityExt.getCreatorId());
        handlerExplainDTO.setLoginUser(detailTabDataGetDTO.getLoginUser());
        handlerExplainDTO.setUserId(detailTabDataGetDTO.getUserId());
        havePermission = ExplainUtil.isEditableOfScope(linkProductField, handlerExplainDTO);

        return havePermission;
    }

    @Override
    public void updateBatchLabelAttr(AddLabelDTO addLabelDTO, List<PaasFormDataEntityExt> addBatchList, Boolean addOrDelete) throws XbbException {
        SupplierUpdateBatchDTO supplierUpdateBatchDTO = new SupplierUpdateBatchDTO();
        BeanUtil.copyProperties(addLabelDTO, supplierUpdateBatchDTO);
        List<SupplierUpdateDTO> supplierList = new ArrayList<>();
        addBatchList.forEach(item->{
            SupplierUpdateDTO supplierUpdateDTO = new SupplierUpdateDTO();
            supplierUpdateDTO.setData(item.getData());
            supplierUpdateDTO.setId(item.getId());
            supplierList.add(supplierUpdateDTO);
        });
        supplierUpdateBatchDTO.setSupplierList(supplierList);
        updateBatch(supplierUpdateBatchDTO);

    }

    @SneakyThrows
    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException{
//        String corpid = saasFormSaveDTO.getCorpid();
        // 团队保存
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), true);
        // 保存供应商负责人
//        userTeamService.saveUserTeam(saasFormSaveDTO);

//        PaasFormDataEntity paasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
//        Long supplierId = paasFormDataEntity.getId();
//        JSONObject dataList = paasFormDataEntity.getData();
//        String supplierName = dataList.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
//        JSONArray productIdArray = dataList.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        // 新工作流不走，新建编辑没用 @date 2021/7/29 11:24
        // 保存供应商关联产品
//        if (BasicConstant.ONE.equals(saasFormSaveDTO.getIsImport()) || (Objects.nonNull(productIdArray) && !productIdArray.isEmpty())) {
//            //新建或编辑可见产品字段
//            Runnable runnable = () -> {
//                try {
//                    saveSupplierProduct(saasFormSaveDTO.getIsNew(), corpid, supplierId, supplierName, productIdArray);
//                } catch (Exception e) {
//                    LOG.error("保存供应商关联产品", e);
//                }
//            };
//            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
//        }
    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
//        String corpid = saasFormSaveDTO.getCorpid();
        // 保存供应商负责人
        // 团队保存
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), true);
//        userTeamService.saveUserTeam(saasFormSaveDTO);

//        PaasFormDataEntity paasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
//        Long supplierId = paasFormDataEntity.getId();
//        JSONObject dataList = paasFormDataEntity.getData();
//        String supplierName = dataList.getString(SupplierEnum.SUPPLIER_NAME.getAttr());
//        JSONArray productIdArray = dataList.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
        // 新工作流不走，新建编辑没用 @date 2021/7/29 11:24
        // 保存供应商关联产品
//        if (BasicConstant.ONE.equals(saasFormSaveDTO.getIsImport()) || (Objects.nonNull(productIdArray) && !productIdArray.isEmpty())) {
//            //新建或编辑可见产品字段
//            Runnable runnable = () -> {
//                try {
//                    saveSupplierProduct(saasFormSaveDTO.getIsNew(), corpid, supplierId, supplierName, productIdArray);
//                } catch (Exception e) {
//                    LOG.error("保存供应商关联产品", e);
//                }
//            };
//            threadPoolBeanConfig.addUpdateDelThreadPool().execute(runnable);
//        }
    }

    private DetailProductVO formatProduct4DetailShow(List<SupplierProductEntity> supplierProductEntityList, PagingProductDTO pagingProductDTO) throws XbbException{
        DetailProductVO detailProductVO = new DetailProductVO();
        Set<Long> productIds = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
            if (BasicConstant.ZERO_LONG.equals(supplierProductEntity.getParentId())) {
                continue;
            }
            productIds.add(supplierProductEntity.getProductId());
        }
        String corpid = pagingProductDTO.getCorpid();
        JSONArray productArray = new JSONArray();
        Map<Long, PaasFormDataEntityExt> productMap = productService.getProductMapByIdIn(productIds, corpid, DelEnum.NORMAL);
        PaasFormExplainEntity productExplains = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        if (Objects.isNull(productExplains)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Map<String, FieldAttrEntity> productExplainMap = ExplainUtil.getExplainMap(productExplains.getExplains(), null);
        for (SupplierProductEntity supplierProductEntity : supplierProductEntityList) {
            PaasFormDataEntityExt paasFormDataEntityExt = productMap.get(supplierProductEntity.getProductId());
            JSONObject json = new JSONObject();
            if (Objects.nonNull(supplierProductEntity.getData())) {
                json = supplierProductEntity.getData();
            }
            for (SupplierProductEnum supplierProductEnum : SupplierProductEnum.values()) {
                if (!UpdateDataTypeEnum.DETAIL.formatShow(supplierProductEnum.getShowType())) {
                    continue;
                }
                String attr = supplierProductEnum.getAttr();
                switch (supplierProductEnum) {
                    case PRODUCT:
                        json.put(attr, supplierProductEntity.getProductId());
                        break;
                    case UNIT:
                        if (Objects.nonNull(paasFormDataEntityExt)) {
                            String unitStr = productModel.getProductUnitTextByValue(supplierProductEntity.getUnit(), productExplainMap.get(ProductEnum.UNIT.getAttr()));
                            json.put(attr, unitStr);
                        }
                        break;
                    default:
                        break;
                }
            }
            // 返回供货产品id
            json.put(BusinessConstant.PRODUCT_SUB_ID, supplierProductEntity.getId());
            productArray.add(json);
        }
        detailProductVO.setProductDataArr(productArray);
        return detailProductVO;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        List<SupplierProductEntity> supplierProductEntityList = new ArrayList<>();
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(SupplierEnum.PRODUCT_LIST.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, SupplierEnum.PRODUCT_LIST.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = getProductMap(corpid, productArr);
                getProductList( supplierProductEntityList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(SupplierEnum.PRODUCT_LIST.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        SupplierProductEntity supplierProductEntity = new SupplierProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            supplierProductEntity.setId(subProductId);
                        }
                        supplierProductEntity.setData(jsonObject);
                        supplierProductEntityList.add(supplierProductEntity);
                    }
                }
            }
        } else {
            supplierProductEntityList = supplierProductModel.getSupplierProductBySupplierId(corpid,dataId);
        }
        JSONArray productArray = new JSONArray();
        for (SupplierProductEntity supplierProductEntity : supplierProductEntityList){
            JSONObject json = supplierProductEntity.getData();
            if (Objects.isNull(json) || json.isEmpty()){
                json = new JSONObject();
                for (SupplierProductEnum supplierProductEnum : SupplierProductEnum.values()){
                    String attr = supplierProductEnum.getAttr();
                    switch (supplierProductEnum){
                        case PRODUCT:
                            json.put(attr,supplierProductEntity.getProductId());
                            break;
                        case UNIT:
                            json.put(attr, supplierProductEntity.getUnit());
                            break;
                        default:
                            break;
                    }
                }
            }
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,supplierProductEntity.getId());
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), formDataValidateProductHelp.formatUnit(supplierProductEntity.getCorpid(),supplierProductEntity.getUnit()));
            }
            productArray.add(json);
        }
        data.put(SupplierEnum.PRODUCT_LIST.getAttr(),productArray);
    }

    /**
     * 删除预付款余额为0的记录
     * @param corpid 公司ID
     * @param deletePayBalanceId 删除预付款ID
     * @return 预付款ID集合
     * @throws XbbException error
     */
    private List<Long> deletePayBalance(String corpid, List<Long> deletePayBalanceId) throws XbbException {
        if(CollectionsUtil.isEmpty(deletePayBalanceId)){
            return deletePayBalanceId;
        }
        try {
            payBalanceService.deleteBatch(deletePayBalanceId, corpid);
        } catch (Exception e) {
            LOG.error("supplierServiceImpl.deletePayBalance 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return deletePayBalanceId;
    }

    @Override
    public Map<Long,String> getSupplierNameMap(List<Long> handoverIdSet, String corpid) throws XbbException {
        Map<Long,String> supplierNameMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (handoverIdSet.isEmpty()){
            return supplierNameMap;
        }
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termsQuery(FieldTypeEnum.DATAID.getAlias(),handoverIdSet));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_SUPPLIER.getType()));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, handoverIdSet.size());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_SUPPLIER.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,searchRequest,PaasFormDataEntity.class);
        for (PaasFormDataEntity entity : esEntities.getContent()){
            supplierNameMap.put(entity.getDataId(),entity.getData().getString(SupplierEnum.SUPPLIER_NAME.getAttr()));
        }
        return supplierNameMap;
    }
}
